﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Linq;
using System.Net.Sockets;

using VirtualShare.Common;
using VirtualShare.Extensions;
using System.Threading;

namespace VirtualShare.Client
{
    static class Program
    {
        static byte[] buffer = new byte[2];

        static TcpClient mainServer;
        static NetworkStream mainStream;
        static BinaryReader mainReader;
        static BinaryWriter mainWriter;

        static TcpListener p2pServer;

        public static Client client;
        static List<Client> clients = new List<Client>();

        static void Main()
        {
            // Chargement des extensions
            string[] dllFiles = Directory.GetFiles(Environment.CurrentDirectory, "*.dll");
            foreach (string dllFile in dllFiles)
                ExtensionsManager.LoadExtension(dllFile);

            Application.EnableVisualStyles();
            //Application.Run(new Main());

            Login("admin", "admin");
            ExtensionsManager.extensions.ForEach(e => e.OnLogin(ref client));
        }

        static void Login(string user, string pass)
        {
            mainServer = new TcpClient();
            mainServer.Connect(Config.host, 2424);

            mainStream = mainServer.GetStream();
            mainReader = new BinaryReader(mainStream);
            mainWriter = new BinaryWriter(mainStream);

            mainWriter.Write((short)PacketType.Login);
            mainWriter.Write(user);
            mainWriter.Write(pass);

            if ((PacketType)mainReader.ReadInt16() == PacketType.LoginFail)
                return;

            new Thread(new ThreadStart(delegate()
                {
                    client = new Client(mainReader);
                    Application.Run(client.form);
                })).Start();

            //mainStream.BeginRead(buffer, 0, 2, new AsyncCallback(OnReceiveData), null);
        }

    }
}
